#include<func.h>
#include<mysql/mysql.h>

int remove_file(MYSQL *db, char *username, char *filename, int netfd) {
    // 构造 SQL 语句
    char sql[1024];
    char results[1024];
    sprintf(sql, "UPDATE FileTable SET tomb=1 WHERE username='%s' AND filename='%s' AND tomb=0", username, filename);

    // 执行 SQL 语句
    if (mysql_query(db, sql)) {
        fprintf(stderr, "%s\n", mysql_error(db));
        strcpy(results,"remove error");
        send(netfd,&results,1024,MSG_NOSIGNAL);

        return -1;
    }

    // 检查受影响的行数
    if (mysql_affected_rows(db) == 0) {
        // 没有找到记录
        strcpy(results,"cannot find file\n");
        send(netfd,&results,1024,MSG_NOSIGNAL);
        return -1;
    }

    strcpy(results,"remove success\n");
    strcat(results,"\n");
    int len = strlen(results);
    send(netfd,len,4,MSG_NOSIGNAL);
    send(netfd,&results,64,MSG_NOSIGNAL);
    return 1;
}

int remove_m(MYSQL *db, char *current_path, int netfd) {
    // 提取 username 和 filename
    char *path = current_path;
    char *username = strtok(path, "/");
    while (path != NULL) {
        username = path;
        path = strtok(NULL, "/");
    }
    char *filename = strrchr(current_path, '/');
    if (filename == NULL) {
        filename = current_path;
    } else {
        filename++;
    }

    // 在数据库中查找记录并标记为删除
    return remove_file(db, username, filename, netfd);
}

